package com.example.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class SendCode {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Value("${short.msg.flag}")
    private boolean flag;
    @Value("${short.msg.key}")
    private String key;


    /**
     * @param code       对应消息模板id
     * @param phone        电话号码
     * @param vilidateCode 验证码
     * @return
     */
    public ShortMsgUtil.Result sendVilidateCode(MsgCode code, String phone, String vilidateCode) throws Exception {
        StringBuffer tplValue = new StringBuffer().append("#app#=").append("&#company#=")
                .append(vilidateCode);
        ShortMsgUtil.Result result = new ShortMsgUtil.Result();
        if (flag) {
            result = ShortMsgUtil.init(key).sendMsg(phone, code.getCode(), tplValue.toString());
            if (result.isSuccess()) {
                redisTemplate.opsForValue().set(RedisKeys.msgKey + phone, vilidateCode, 5, TimeUnit.MINUTES);
            }
        } else {
            redisTemplate.opsForValue().set(RedisKeys.msgKey + phone, vilidateCode, 5, TimeUnit.MINUTES);
            result.setError_code(0);
            result.setReason("短信发送成功");
        }
        return result;
    }

    /**
     * 发送短信
     *
     * @param code 对应消息模板id
     * @param phone
     * @param msg
     * @return
     * @throws Exception
     */
    public ShortMsgUtil.Result sendMsg(MsgCode code, String phone, String msg) throws Exception {
        StringBuffer tplValue = new StringBuffer().append("#app#=").append("&#company#=")
                .append(msg);
        ShortMsgUtil.Result result = new ShortMsgUtil.Result();
        if (flag) {
            result = ShortMsgUtil.init(key).sendMsg(phone, code.getCode(), tplValue.toString());
        } else {
            result.setError_code(0);
            result.setReason("短信发送成功");
        }
        return result;
    }

    /**
     * 验证验证码是否正确
     *
     * @param phone
     * @param validateCode
     * @return
     */
    public boolean checkVilidateCode(String phone, String validateCode) {
        String rcode = (String) redisTemplate.opsForValue().get(RedisKeys.msgKey + phone);
        if (rcode != null && rcode.equals(validateCode)) {
            return true;
        }
        return false;
    }

    /**
     * 清除验证码
     *
     * @param phone
     */
    public void cleanVilidateCode(String phone) {
        redisTemplate.delete(RedisKeys.msgKey + phone);
    }

}
